package com.finalist.controller.travel.weixin;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.finalist.controller.shop.BaseController;
import com.finalist.entity.Departure;
import com.finalist.entity.Destination;
import com.finalist.entity.Member;
import com.finalist.entity.Product;
import com.finalist.entity.ProductCategory;
import com.finalist.entity.Review;
import com.finalist.entity.Order.Category;
import com.finalist.service.DepartureService;
import com.finalist.service.DestinationService;
import com.finalist.service.MemberService;
import com.finalist.service.OrderService;
import com.finalist.service.ProductCategoryService;
import com.finalist.service.ProductService;
import com.finalist.service.ReviewParaService;
import com.finalist.service.ReviewService;
import com.finalist.util.DateUtil;
import com.finalist.vo.ProductResult;

@Controller("travelWeixinIndexController")
@RequestMapping("/travel/weixin")
public class IndexController extends BaseController{
	
	protected static final String VIEW = "/travel/weixin/index/";
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Resource(name = "productServiceImpl")
	private ProductService productService;
	
	@Resource(name = "productCategoryServiceImpl")
	private ProductCategoryService productCategoryService;
	
	@Resource(name = "destinationServiceImpl")
	private DestinationService destinationService;
	
	@Resource(name = "reviewServiceImpl")
	private ReviewService reviewService;
	
	@Resource(name = "departureServiceImpl")
	private DepartureService departureService;
	
	@Resource(name = "orderServiceImpl")
	private OrderService orderService;
	
	@Resource(name = "reviewParaServiceImpl")
	private ReviewParaService reviewParaService;
	
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	
	@RequestMapping("/index")
	public String index(ModelMap model){
		
		List<Departure> newDeparture = new ArrayList<Departure>();
 		List<Departure> departures = departureService.findAll();
 		newDeparture.addAll(departures);
		Collections.sort(newDeparture,new Comparator<Departure>(){
			public int compare(Departure o1, Departure o2) {
			       String s1 = o1.getName();
			            String s2 = o2.getName();
			            return Collator.getInstance(Locale.CHINESE).compare(s1, s2); 
			}
			        });
		model.addAttribute("departures",newDeparture);
		
		List<ProductCategory> newProductCategory = new ArrayList<ProductCategory>();
		List<ProductCategory> categorys = productCategoryService.findAll();
		newProductCategory.addAll(categorys);
		Collections.sort(newProductCategory,new Comparator<ProductCategory>(){
			public int compare(ProductCategory o1, ProductCategory o2) {
				String s1 = o1.getName();
				String s2 = o2.getName();
				return Collator.getInstance(Locale.CHINESE).compare(s1, s2); 
			}
		});
		model.put("categorys", newProductCategory);
		
		List<Destination> newDestination = new ArrayList<Destination>();
		List<Destination> destinations = destinationService.findAll();
		newDestination.addAll(destinations);
		Collections.sort(newDestination,new Comparator<Destination>(){
			public int compare(Destination o1, Destination o2) {
				String s1 = o1.getName();
				String s2 = o2.getName();
				return Collator.getInstance(Locale.CHINESE).compare(s1, s2); 
			}
		});
		model.put("destinations",newDestination );
		
		model.put("products", productService.findProductByPage(1));
		model.put("dates", getDates());
		return VIEW + "index";
	}
	
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(){
		return "TEST";
	}
	
	@RequestMapping("/product/detail")
	public String detail(Long productId ,HttpServletRequest re, ModelMap model){
		Member member = (Member)re.getAttribute("currentUser");
		Product product = productService.find(productId);
		model.put("isMobile", re.getParameter("isMobile"));
		model.put("product", product);
		model.put("admin", product.getAdmin());
		model.put("reviews", reviewService.findPage(product, 1));
		model.put("members",memberService.findByProduct(product,1));
		long orders =  orderService.finishOrderCount(member);
		if(orders>0){
			model.put("canEvaluation", 1);
		}else{
			model.put("canEvaluation", -1);
		}
		return VIEW + "detail";
	}
	
	@RequestMapping(value="/message", method=RequestMethod.GET)
	@ResponseBody
	public String authenticate(String signature, String timestamp, String nonce, String echostr) {
		return echostr;
	}
	
	@RequestMapping(value = "/ajaxProduct" , method = RequestMethod.GET)
	@ResponseBody
	public ProductResult ajaxProduct(HttpServletRequest re,Long[] categorys , String[] origins , String[] dests,String[] starts,String[] timeCycle,Integer page){
		List<Product> products = productService.findProductByCondition(page, null, null, categorys, origins, dests, starts, timeCycle);
		ProductResult result = new ProductResult();
		if(page == 1 && (products==null || products.size() == 0)){
			result.setType("noAll");
			List<Product> _products = null;
			switch (0) {
			case 0:
				if(categorys==null || categorys.length == 0){
				}else{
					_products = productService.findProductByCondition(1, null, null, categorys, null, null, null, null);
					if(_products!=null && _products.size()!=0){
						result.setProducts(_products);
						return result;
					}
				}
			case 1:
				if(dests==null || dests.length == 0){
				}else{
					_products = productService.findProductByCondition(1, null, null, null, null, dests, null, null);
					if(_products!=null && _products.size()!=0){
						result.setProducts(_products);
						return result;
					}
				}
			case 2:
				if(origins==null || origins.length == 0){
				}else{
					_products = productService.findProductByCondition(1, null, null, null, origins, null, null, null);
					if(_products!=null &&_products.size()!=0){
						result.setProducts(_products);
						return result;
					}
				}
			case 3:
				if(starts==null || starts.length == 0){
				}else{
					_products = productService.findProductByCondition(1, null, null, null, null, null, starts, null);
					if(_products!=null &&_products.size()!=0){
						result.setProducts(_products);
						return result;
					}
				}
			case 4:
				if(timeCycle==null || timeCycle.length == 0){
				}else{
					_products = productService.findProductByCondition(1, null, null, null, null, null, null, timeCycle);
					if(_products!=null &&_products.size()!=0){
						result.setProducts(_products);
						return result;
					}
				}
			default:
				return null;
			}
		}else{
			result.setType("all");
			result.setProducts(products);
			return result;
		}
	}
	
	@RequestMapping(value="/message", method=RequestMethod.POST)
	public void message(HttpServletRequest request, HttpServletResponse response) {
		logger.info("微信发起请求!");
		response.setContentType("application/xml");
		response.setCharacterEncoding("UTF-8");
		try {
			response.getWriter().write("1111");
		} catch(Exception e) {
			logger.error("message error: ", e);
		}
	}
	
	public List<String> getDates(){
		List<String> dates =  new ArrayList<String>(); 
		Date now = new Date();
		for(int i = 0 ; i< 12 ; i++){
			dates.add(DateUtil.getYear(DateUtil.addMonth(now, i))+"-"+DateUtil.getMonth(DateUtil.addMonth(now, i)));
		}
		return dates;
		
	}
	
	@RequestMapping(value = "/ajaxReviews" , method = RequestMethod.GET)
	@ResponseBody
	public List<Review> ajaxReviews(Integer page,long productId){
		Product product = productService.find(productId);
		return reviewService.findPage(product, page);
	}
	@RequestMapping(value = "/ajaxMember" , method = RequestMethod.GET)
	@ResponseBody
	public List<Member> ajaxMember(Integer page,long productId){
		Product product = productService.find(productId);
		return memberService.findByProduct(product,page);
	}
	
	
	public LinkedHashMap<String, Object> getConditions(int flag,int num , LinkedHashMap<String, Object> conditions){
		
		return null;
	}
	
}
